/* eslint-disable react/prop-types */

import React, { Component } from "react";
import { Link } from "react-router";
import PropTypes from "prop-types";
import StatusPanel from "components/StatusPanel.js";
import ReactModal from "react-modal";

class WorkEdit extends Component {

  constructor(props) {
    super(props);
    this.state = {
      name: props.work.name,
      categoryId: props.work.categoryId,
      description: props.work.description,
      wordCount: props.work.description ? props.work.description.length : '0'
    };
    this.handleCategoryChanged = this.handleCategoryChanged.bind(this);
    this.handleNameChanged = this.handleNameChanged.bind(this);
    this.handleDescriptionChanged = this.handleDescriptionChanged.bind(this);
    this.updateMyWork = this.updateMyWork.bind(this);
    this.publishMyWork = this.publishMyWork.bind(this);
    this.handleCloseModal = this.handleCloseModal.bind(this);
    this.handleOpenModal = this.handleOpenModal.bind(this);
    this.setModalText = this.setModalText.bind(this);
  }

  handleNameChanged(event) {
    this.setState({
      name: event.target.value,
      nameLength: event.target.value.length
    });
  }

  handleCategoryChanged(event) {
    this.setState({
      categoryId: event.target.value
    });
  }

  handleDescriptionChanged(event) {
    this.setState({
      description: event.target.value,
      wordCount: event.target.value.length
    });
  }

  setModalText(text) {
    this.setState({
      showModal: true,
      errorText: text
    })
  }

  handleOpenModal() {
    this.setState({ showModal: true });
  }

  handleCloseModal() {
    this.setState({
      showModal: false,
      errorText: '错误',
    });
  }

  updateMyWork() {
    let { work, myWorkAction } = this.props;
    let { name, description, categoryId } = this.state;
    name = name || '';
    description = description || '';
    if (description.length > 800) {
      this.setModalText('作品描述最多只允许输入800字');
      return false;
    }
    if (name.length > 20) {
      this.setModalText('作品名称最多只允许输入20字');
      return false;
    }
    this.setState({
      isPublishing: false,
      isPublished: false,
      isSaving: true,
      isSaved: false,
      isErrorOccured: false
    })
    myWorkAction.updateMyWorkById(work.id,
      name,
      undefined,
      categoryId,
      description)
      .then(() => {
        this.setState({
          isSaving: false,
          isSaved: true
        })
      }, () => {
        this.setState({
          isSaving: false,
          isSaved: false,
          isErrorOccured: true
        })
      })
      .then(() => {
        return new Promise(resolve => window.setTimeout(resolve, 1000));
      }).then(() => {
        this.setState({
          isSaving: false,
          isSaved: false,
          isErrorOccured: false
        });
      });
  }

  publishMyWork() {
    let { work, router, myWorkAction } = this.props;
    let { name, description, categoryId } = this.state;
    name = name || '';
    description = description || '';
    if (description.length > 800) {
      this.setModalText('作品描述最多只允许输入800字');
      return false;
    }
    if (name.length > 20) {
      this.setModalText('作品名称最多只允许输入20字');
      return false;
    }
    this.setState({
      isPublishing: true,
      isPublished: false,
      isSaving: false,
      isSaved: false,
      isErrorOccured: false
    });
    myWorkAction.updateMyWorkById(work.id,
      name, undefined, categoryId, description).then(() => {
      return myWorkAction.changeMyWorkStatus(work.id, 'PUBLIC');
    }).then(() => {
      this.setState({
        isPublishing: false,
        isPublished: true
      });
    }).catch(() => {
      this.setState({
        isPublishing: false,
        isPublished: false,
        isErrorOccured: true
      });
    }).then(() => {
      return new Promise(resolve => window.setTimeout(resolve, 1000));
    }).then(() => {
      router.push('my/published');
    });
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      name: nextProps.work.name,
      categoryId: nextProps.work.categoryId,
      description: nextProps.work.description,
      wordCount: nextProps.work.description ? nextProps.work.description.length : '0'
    });
  }

  render() {
    let { categories, location, work } = this.props;
    let returnUrl = location.query.returnUrl || `work/${work.id}/detail`;
    return (
      <div id="work-edit">
        <div>
          <div className="edit-group">
            <label>作品名称</label>
            <input id="work-name" className={this.state.nameLength > 20 ? 'overflow' : ''} type="text" value={this.state.name} onChange={this.handleNameChanged} />
            <span style={{ display: this.state.nameLength > 20 ? 'block' : 'none' }} className="validate-msg">*标题请勿超过20个字符</span>
          </div>
          <div className="edit-group">
            <label>作品分类</label>
            <select id="categories" value={this.state.categoryId} onChange={this.handleCategoryChanged}>
              {
                categories && categories.map(c => {
                return c.categoryId === this.props.work.categoryId ?
                  <option key={c.categoryId} value={c.categoryId} selected>{c.categoryName}</option> :
                  <option key={c.categoryId} value={c.categoryId}>{c.categoryName}</option>
              })
              }
            </select>
          </div>
          <div className="edit-group">
            <label>作品描述（选填）</label>
            <textarea value={this.state.description} className={this.state.wordCount > 800 ? 'overflow' : ''} onChange={this.handleDescriptionChanged}>
            </textarea>
            <span className="word-count">{(this.state.wordCount || 0) + ' / 800'}</span>
            <span style={{ display: this.state.wordCount > 800 ? 'block' : 'none' }} className="validate-msg">*描述请勿超过800个字符</span>
          </div>
        </div>
        <div className="btn-group">
          <Link to={returnUrl}>取消</Link>
          {work.status === 'PRIVATE' && <button className="save" onClick={this.updateMyWork}>保存</button>}
          <button className="publish" onClick={this.publishMyWork}>发布</button>
        </div>
        <StatusPanel
          isShow={this.state.isPublishing}
        >
          <div className="loading"><i className="icon icon-spinner2"></i></div>
          <div className="body">正在发布...</div>
          <div className="status-footer">发布作品可能需要等待一定时间。</div>
        </StatusPanel>
        <StatusPanel
          isShow={this.state.isPublished}
        >
          <div>
            <i className="icon icon-alert_big_right success">
              <span className="path1"></span>
              <span className="path2"></span>
            </i>
          </div>
          <div className="body success">作品已成功发布</div>
        </StatusPanel>
        <StatusPanel
          isShow={this.state.isSaving}
        >
          <div className="loading"><i className="icon icon-spinner2"></i></div>
          <div className="body">正在保存...</div>
          <div className="status-footer">保存作品可能需要等待一定时间。</div>
        </StatusPanel>
        <StatusPanel
          isShow={this.state.isSaved}
        >
          <div>
            <i className="icon icon-alert_big_right">
              <span className="path1"></span>
              <span className="path2"></span>
            </i>
          </div>
          <div className="body success">作品已保存</div>
        </StatusPanel>
        <StatusPanel
          isShow={!!this.state.isErrorOccured}
        >
          <div>
            <i className="icon icon-alert_big_error"></i>
          </div>
          <div className="body failed">发生错误</div>
        </StatusPanel>
        <ReactModal
          isOpen={this.state.showModal}
          contentLabel="onRequestClose Example"
          onRequestClose={this.handleCloseModal}
          portalClassName="ReactModalPortal"
          className={{
            base: 'Modal'
          }}
          overlayClassName={{
            base: 'confirm-overlay-base',
            afterOpen: 'confirm-overlay-open',
            beforeClose: 'confirm-overlay-close'
          }}>
          <p className="modal-text">{this.state.errorText}</p>
          <button
            className="modal-close"
            onClick={this.handleCloseModal}>确定</button>
        </ReactModal>
      </div>
    )
  }
}

WorkEdit.propTypes = {
  work: PropTypes.shape({
    workId: PropTypes.string,
    workName: PropTypes.string,
    workAuthorId: PropTypes.string,
    workAuthorName: PropTypes.string,
    workCategoryId: PropTypes.string,
    workCategoryName: PropTypes.string,
    workDateTime: PropTypes.string,
    workLikes: PropTypes.number,
    workDescription: PropTypes.string,
    workLiked: PropTypes.bool
  }),
  myWorkAction: PropTypes.object
}

export default WorkEdit